from intermine.webservice import Service
import string
import re
import pdb

def yeastmine(geneInput='AGA1',outFile='yeastmine_out.tsv',mode='Seq+UTRs',utrLen=50,ORFhomo=50,KOhomo=18):
	'''Writes a table from Yeastmine for cloning design given a list of genes.
		geneInput: 'AGA1, AGA2' or ['AGA1', 'AGA2']
		outFile: '/path/file.tsv'
        
		Output format: Gene | Location | 5'UTR | ORF | 3'UTR
        
		Download and install 'intermine': >>sudo easy_install intermine
		For further documentation: http://www.intermine.org/wiki/PythonClient
		Thomas Stevens - Lim Lab 2012
		'''
    
	service = Service("http://yeastmine.yeastgenome.org/yeastmine/service")
	strandList = ['?','+','-']

	fout = open(outFile,'w')
	#Headers
	fout.write('\t'.join(['Gene','Location','5-UTR','ORF','3-UTR']) + '\n')

	if type(geneInput) == str:
		geneList = re.split('\W+',geneInput)
	else:
		geneList = geneInput

	for gene in geneList:
		#get position
		query = service.new_query()
		query.add_view(
					   "Gene.chromosome.organism.name",		#0
					   "Gene.symbol",						#1
					   "Gene.chromosome.primaryIdentifier",	#2
					   "Gene.chromosomeLocation.strand",	#3
					   "Gene.chromosomeLocation.start",		#4
					   "Gene.chromosomeLocation.end"		#5
				   )
		query.add_constraint("Gene.symbol", "=", gene, "A")
		query.add_constraint("Gene.chromosome.organism.name","=", "Saccharomyces cerevisiae", "A")

		############
		#pdb.set_trace()
		############
		
		for row in query.results("tsv"):
			resultsList = row.split('\t')
			print resultsList
			organism,geneName,chrID,strand,startNum,endNum = resultsList
			strand = int(strand)
			startNum = int(startNum)
			endNum = int(endNum)


		############
		#pdb.set_trace()
		############

		#get chr seq
		query = service.new_query()
		query.add_view("Chromosome.sequence.residues")
		query.add_constraint("Chromosome.primaryIdentifier", "=", chrID, "A")
		
		for seq in query.results("tsv"):
			if strand==-1:
				# - strand
				comp = string.maketrans('ATCG','TAGC')
				seq = seq.translate(comp)
				orf = seq[startNum-1:endNum][::-1]
				utr5 = seq[endNum:endNum+utrLen][::-1]
				utr3 = seq[startNum-utrLen-1:startNum-1][::-1]
			else:
				# + strand
				orf = seq[startNum-1:endNum]
				utr5 = seq[startNum-utrLen-1:startNum-1]
				utr3 = seq[endNum:endNum+utrLen]
		location = chrID+':'+str(startNum)+'-'+str(endNum)+'('+strandList[strand]+')'
		fout.write('\t'.join([geneName,location,utr5,orf,utr3]) + '\n')
	
	fout.close()

